#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
int main(){
    int fd = open("test.txt",O_CREAT|O_RDWR|O_TRUNC,0644);
    if (fd == -1){
        perror("open error");
        exit(1);
    }
    /*扩展文件大小
    lseek(fd,10,SEEK_END);
    write(fd,"\0",1);
    */
    ftruncate(fd,20); //同样也能扩展文件大小

    int len = lseek(fd,0,SEEK_END);
    char *p = mmap(NULL,len,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
    if (p == MAP_FAILED){
        perror("mmap error");
        exit(1);
    }
    //使用p对文件进行读写操作
    strcpy(p,"hello mmap");//写操作
    printf("---%s\n",p);//直接读
    close(fd);//关闭打开的文件
    int ret = munmap(p,len);
    if (ret == -1){
        perror("munmap error");
        exit(0);
    }
    return 0;
}